package fi.iki.juri.units.generator;

import java.util.ArrayList;
import java.util.Collection;

import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

public class XPathCompiler {
	private final XPath xpath;

	public class ExpressionWrapper {
		private final XPathExpression expr;

		public ExpressionWrapper(final XPathExpression expr) {
			this.expr = expr;
		}
		
		public String readString(final Element parent) {
			try {
				final String v = (String)expr.evaluate(parent, XPathConstants.STRING);
				v.trim();
				return "".equals(v) ? null : v;
			} catch (XPathExpressionException e) {
				throw new RuntimeException(e);
			}
		}
		
		public Collection<String> readCollection(final Element parent) {
			try {
				final NodeList nodeList = (NodeList)expr.evaluate(parent, XPathConstants.NODESET);
				final Collection<String> texts = new ArrayList<String>();
				for (final Element elem : new IterableNodeList(nodeList)) {
					texts.add(elem.getTextContent());
				}
				return texts;
			} catch (XPathExpressionException e) {
				throw new RuntimeException(e);
			}
		}
	}
	
	public XPathCompiler() {
		XPathFactory factory = XPathFactory.newInstance();
		this.xpath = factory.newXPath();
	}
	
	public ExpressionWrapper compile(final String str) {
		try {
			return new ExpressionWrapper(xpath.compile(str));
		} catch (XPathExpressionException ex) {
			throw new RuntimeException(ex);
		}
	}
}
